<?php

namespace App\Http\Controllers\Home;

use App\Models\Configs;
use App\Models\Users;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Jenssegers\Agent\Agent;
use Laravel\Socialite\Facades\Socialite;
use Mrgoon\AliSms\AliSms;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class AuthController extends Controller
{
    use AuthenticatesUsers;

    protected $chanel_id = 0;//设置导航选中标志

    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
        view()->share('chanel_id',$this->chanel_id);
    }

    public function login(Request $request)
    {
        if($request->method() == 'POST'){
            $data = $request->all();
            $credentials['username'] = $data['username'];
            $credentials['password'] = $data['password'];
            if ($this->guard()->attempt($credentials, $request->has('remember'))) {
                $request->session()->regenerate();
                $this->clearLoginAttempts($request);
                $update = [
                    'login_ip' => $request->ip(),
                    'login_at' => Carbon::now(),
                ];
                if(isset($data['type'])){
                    switch($data['type']){
                        case 'weibo':
                            $update['weibo_id'] = $data['three_id'];
                            break;
                        case 'qq':
                            $update['qq_id'] = $data['three_id'];
                            break;
                    }
                }
                auth()->user()->update($update);
                $previous = cache()->get('previous');
                $previous = empty($previous) ? route('user.index.index') : $previous;
                return $this->writeJson(0,$previous);
            }
            return $this->writeJson(1,null,'账号或者密码错误');
        }else{
            cache()->add('previous',url()->previous(),600);
            return view('home.auth.login');
        }
    }

    public function register(Request $request)
    {
        if($request->method() == 'POST'){
            $data = $request->all();

            //验证短信验证码
            $cache = cache()->get('sms-'.$data['username']);
            //过期
            if(empty($cache)) return $this->writeJson(1,null,'验证码已过期');
            //正确
            if($cache['code'] != $data['code']) return $this->writeJson(1,null,'验证码输入错误');
            //删除
            cache()->delete('sms-'.$data['username']);

            //字段验证
            $rules = [
                'username' => 'required|unique:users',
                'code'     => 'required',
                'password' => 'required|min:6|confirmed',
                'email'    => 'required|email|unique:users',
            ];
            $msgs = [
                'username.required' => '请填写手机号码',
                'username.unique'   => '手机号已经注册',
                'code.required'     => '请填写短信验证码',
                'password.required' => '请输入密码',
                'password.min'      => '密码最少6位',
                'password.confirmed'=> '确认密码不一致',
                'email.required'    => '请填写邮箱账号',
                'email.email'       => '邮箱账号格式错误',
                'email.unique'      => '邮箱账号已经存在',
            ];
            $validator = validator()->make($data, $rules ,$msgs);
            if ($validator->fails()) {
                return $this->writeJson(1,null,$validator->errors()->first());
            }
            //获取积分规则
            $setting = Configs::info('integral');
            $webSetting = Configs::info('setting');
            $insert = $data;
            $insert['password'] = bcrypt($insert['password']);
            $insert['register_ip']= $request->ip();
            $insert['name']      = $insert['name'] ?? $this->randName();
            $insert['avatar'] = isset($insert['avatar']) ? urldecode($insert['avatar']) : $webSetting['default_avatar'];
            $insert['integral']  = $setting['register'];
            $insert['login_at']  = Carbon::now();
            $insert['login_ip']  = $request->ip();
            if(isset($data['type'])){
                switch($data['type']){
                    case 'weibo':
                        $insert['weibo_id'] = $data['three_id'];
                        break;
                    case 'qq':
                        $insert['qq_id'] = $data['three_id'];
                        break;
                }
            }
            $resault = Users::create($insert);
            if($resault === false){
                return $this->writeJson(1,null,'注册失败');
            }else{
                $credentials['username'] = $data['username'];
                $credentials['password'] = $data['password'];
                if ($this->guard()->attempt($credentials, $request->has('remember'))) {
                    $request->session()->regenerate();
                    return $this->writeJson(0,route('user.index.index'));
                }
            }
        }else{
            return view('home.auth.register');
        }

    }

    public function sms(Request $request)
    {
        try{
            $type = $request->get('type','');
            $info = Users::where('username',$request->mobile)->first();
            if(empty($type)){
                //验证重复性
                if($info) return $this->writeJson(1,null,'该手机账号已注册');
            }else{
                if(!$info) return $this->writeJson(1,null,'手机账号不存在');
            }
            $cache = cache()->get('sms-'.$request->mobile);
            //20秒的频繁验证
            if($cache && Carbon::now()->timestamp - $cache['time'] < 20){
                return $this->writeJson(1,null,'您的操作太频繁');
            }
            $code = rand(100000,999999);//SMS_141730025  异地登录提醒     SMS_141730027  注册验证码
            $result = (new AliSms())->sendSms($request->mobile, 'SMS_141730027', ['code'=> $code]);
            if($result->Code == 'OK'){
                //保存验证码到缓存用于验证
                $time = Carbon::now()->timestamp;
                //2分钟的过期时间
                cache()->add('sms-'.$request->mobile,['code'=>$code,'time'=>$time],120);
                return $this->writeJson(0);
            }else{
                return $this->writeJson(1,$result,'发送短信失败');
            }
        }catch(\Exception $e){
            return $this->writeJson(1,null,'发送短信失败');
        }
    }


    public function find(Request $request){

        if($request->method() == 'POST'){
            $data = $request->all();
            $user = Users::where('username',$data['username'])->first();
            if(empty($user)) return $this->writeJson(1,null,'手机账号不存在');

            //验证短信验证码
            $cache = cache()->get('sms-'.$data['username']);
            //过期
            if(empty($cache)) return $this->writeJson(1,null,'验证码已过期');
            //正确
            if($cache['code'] != $data['code']) return $this->writeJson(1,null,'验证码输入错误');
            //删除
            cache()->delete('sms-'.$data['username']);

            //字段验证
            $rules = [
                'username' => 'required',
                'code'     => 'required',
                'password' => 'required|min:6|confirmed',
            ];
            $msgs = [
                'username.required' => '请填写手机号码',
                'code.required'     => '请填写短信验证码',
                'password.required' => '请输入新密码',
                'password.min'      => '密码最少6位',
                'password.confirmed'=> '确认密码不一致',
            ];
            $validator = validator()->make($data, $rules ,$msgs);
            if ($validator->fails()) {
                return $this->writeJson(1,null,$validator->errors()->first());
            }
            $user->update(['password'=>bcrypt($data['password'])]);
            return $this->writeJson(0,route('home.auth.login'));
        }else{
            return view('home.auth.find');
        }
    }


    /**
     * 退出登录
     * @param Request $request
     * @return mixed
     */
    public function logout()
    {
        $this->guard()->logout();
        request()->session()->regenerate();
        return redirect(route('home.index.index'));
    }


    protected function randName(){
        $str = "1234567890qwertyuiopasdfghjklzxcvbnm";
        return substr(str_shuffle($str),mt_rand(0,strlen($str)-11),10);
    }


    public function qqLogin(){
        return Socialite::driver('qq')->redirect();
    }

    public function qqReturn(){
        try{
            //授权成功获取授权用户信息
            $qq = Socialite::driver('qq')->user();
            //查找用户记录
            $user = Users::where('qq_id',$qq->id)->first();
            $agent = new Agent();
            if($user){
                //直接登录
                auth()->login($user);
                if($agent->isMobile()){
                    return redirect(route('wap.user.index'));
                }else{
                    return redirect(route('user.index.index'));
                }
            }else{
                //获取账户信息，并跳转到绑定账户信息界面
                $three = [
                    "type" => 'qq',
                    "idstr" => $qq->id,
                    "email" => $qq->email,
                    "name" => $qq->user['nickname'],
                    "avatar" => $qq->avatar,
                ];
                if($agent->isMobile()){
                    return view('wap.auth.binding',compact('three'));
                }else{
                    return view('home.auth.binding',compact('three'));
                }
            }
        }catch(\Exception $e){
            abort(500, $e->getMessage());
        }
    }

    public function weiBoLogin(){
//        $three = [
//            "type" => 'weibo',
//            "email" => '',
//            "idstr" => 255655544452,
//            "name" => '永和',
//            "avatar" => 'http://liange.bh/img/login_qq.png',
//        ];
//        $agent = new Agent();
//        if($agent->isMobile()){
//            return view('wap.auth.binding',compact('three'));
//        }else{
//            return view('home.auth.binding',compact('three'));
//        }
        return Socialite::driver('weibo')->redirect();
    }

    public function weiBoReturn(Request $request){
        $data = $request->all();
        //取消授权
        if(isset($data['error_code']) && $data['error_code'] == 21330){
            return redirect(route('home.auth.login'));
        }
        try{
            //授权成功获取授权用户信息
            $weibo = Socialite::driver('weibo')->user();
            //查找用户记录
            $user = Users::where('weibo_id',$weibo->id)->first();
            $agent = new Agent();
            if($user){
                //直接登录
                auth()->login($user);
                if($agent->isMobile()){
                    return redirect(route('wap.user.index'));
                }else{
                    return redirect(route('user.index.index'));
                }
            }else{
                //获取账户信息，并跳转到绑定账户信息界面
                $three = [
                    "type" => 'weibo',
                    "email" => $weibo->email,
                    "idstr" => $weibo->id,
                    "name" => $weibo->nickname,
                    "avatar" => $weibo->avatar,
                ];
                if($agent->isMobile()){
                    return view('wap.auth.binding',compact('three'));
                }else{
                    return view('home.auth.binding',compact('three'));
                }
            }
        }catch(\Exception $e){
            abort(500, $e->getMessage());
        }
    }


}